package singleton.v1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * DCL双检查锁机制
 * @author wanglong
 * @createDate: 2019年3月24日 下午10:49:20
 */
public class SingletonSafe1_2 {

	/**
	 * volatile作用：1.禁止指令排序优化 2.共享变量修改立即写入主内存
	 */
	private static volatile SingletonSafe1_2 object;
	
	private SingletonSafe1_2() {}
	
	private static SingletonSafe1_2 getInstance() {
		try {
			if(object == null) {
				Thread.sleep(3000);
				synchronized (SingletonSafe1_2.class) {
					if(object == null) {
						object = new SingletonSafe1_2();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
	
	
	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					SingletonSafe1_2 object = SingletonSafe1_2.getInstance();
					System.out.println(object);
				}
			}).start();
		}
	}

}
